<!--
富文本组件：用法：
import richTextEditor from "@/components/richTextEditor";
<richTextEditor v-bind:text="form.detail" v-on:editor-change="editorChange"></richTextEditor>

components: {
    richTextEditor
  },
  
  editorChange(html) {
      this.form.detail = html;
    },
-->
<template>
  <div  v-loading="imageLoading"
        element-loading-text="请稍等，图片上传中">
    <quill-editor
      :disabled="disabled"
      ref="newEditor"
      :options="newOption"
      v-model="editorContent"
      @change="onEditorChange($event)">
    </quill-editor>
     <el-upload
      ref="upload"
      :action="uploadFileUrl"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :data="fileOtherData"
       style="display:none">
      <el-button size="small" type="primary" :id="uniqueId">点击上传</el-button>         
     </el-upload>
  </div>
</template>

<script>
  import { quillEditor } from 'vue-quill-editor'
  import Quill from 'quill'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import { get } from "@/utils/request.js";
  export default {
    props: ['text', 'editorId' ,'disabled','noImage'],
    components: {
      quillEditor
    },
    data(){
      return {
        uploadFileUrl: '',
        editorContent: '',
        uniqueId: '',
        imgPercent: 0,
        imageLoading: false,
        newOption: {
          placeholder: '请填写详情',
          strict: false,//should be false for ignore unexpected update
          modules:{
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
              ['blockquote'],//, 'code-block'

              [{'header': 1}, {'header': 2}],               // custom button values
              [{'list': 'ordered'}, {'list': 'bullet'}],
              [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
              [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
              // [{'direction': 'rtl'}],                         // text direction
              [{'header': [1, 2, 3, 4, 5, 6, false]}],

              [{'color': []}, {'background': []}],          // dropdown with defaults from theme
              // [{'font': []}],
              [{'align': []}],
              ['link', 'image']
            ]
          }
        },
        addImgRange: '',//全局参数，每次添加图片时记录当前索引和长度
        // 默认额外上传数据
        fileOtherData: {
          type: Object,
          default: function() {
            return {
              key: "",
              policy: "",
              OSSAccessKeyId: "",
              success_action_status: 200,
              signature: ""
            };
          }
        },
        dir:'richTextImage',
      }
    },
    computed: {
    },
    methods: {
      onEditorChange({ editor, html, text }) {
        let vm = this;
        vm.$emit('editor-change', html);
      },
      handleAvatarSuccess(res, file) {
         let vm = this
        const url =  vm.uploadFileUrl + "/" + vm.fileOtherData.key;
        vm.imageLoading = false;
        console.log(url);
        if (url != null && url.length > 0) {
          let index = vm.addImgRange != null?vm.addImgRange.index:0 // 获取插入时的位置索引，如果获取失败，则插入到最前面
          vm.$refs.newEditor.quill.insertEmbed(index , 'image', url,Quill.sources.USER)
          var img = new Image()
          img.src = url
          vm.$refs.newEditor.quill.formatText(index, index + 1, 'width', 100 + '%');
        } else{
          this.$message.error('图片插入失败');
        }
        this.$refs['upload'].clearFiles() // 插入成功后清除input的内容
      },
      async beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/png 格式!');
          return false;
        }else{
          this.imageLoading = true;
        }
        let vm=this;
        await get("/file/getPolicyUploadInfo", { dir: vm.dir }).then(res => {
          vm.fileOtherData.key = vm.dir + "/" + new Date().getTime() + file.name;
          vm.fileOtherData.policy = res.data.data.policy;
          vm.fileOtherData.OSSAccessKeyId = res.data.data.accessid;
          vm.fileOtherData.signature = res.data.data.signature;
          vm.uploadFileUrl = res.data.data.host;
        });
        return true;  
      }
    },
    created: function () {
      let vm = this
      console.log(vm.editorId)
      vm.imgPercent = 0
      vm.editorContent = vm.text
      vm.uniqueId = vm.editorId?vm.editorId:'inputImg'
      if(vm.noImage){
        this.newOption.modules.toolbar = [
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
          ['blockquote'],//'code-block'

          [{'header': 1}, {'header': 2}],               // custom button values
          [{'list': 'ordered'}, {'list': 'bullet'}],
          [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
          [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
          // [{'direction': 'rtl'}],                         // text direction

          [{'header': [1, 2, 3, 4, 5, 6, false]}],

          [{'color': []}, {'background': []}],          // dropdown with defaults from theme
          // [{'font': []}],
          [{'align': []}],
          // ['link', 'image']
        ]
      }
    },
    watch:{
      text: function () {
        let vm = this
        console.log('请求回来的文本数据',vm.text)
        vm.editorContent = vm.text
      }
    },
    mounted() {
      let vm =this
      // you can use current editor object to do something(quill methods)
      var imgHandler = async function(image) {
        vm.addImgRange = vm.$refs.newEditor.quill.getSelection()
        if (image) {
          var fileInput = document.getElementById(vm.uniqueId) //隐藏的file文本ID
          fileInput.click() //加一个触发事件
        }
      }
      vm.$refs.newEditor.quill.getModule("toolbar").addHandler("image", imgHandler)
    }
  }
</script>